/*
 * LoRa E32-TTL-100
 * Start device or reset to send a message
 * https://www.mischianti.org
 *
 * Board Wemos D1 mini
 *
 * E32-TTL-100----- Wemos D1 mini
 * M0         ----- GND
 * M1         ----- GND
 * TX         ----- PIN D2 (PullUP) 4.7K
 * RX         ----- PIN D3 (PullUP) 4.7K
 * AUX        ----- (PullUP) 4.7K
 * VCC        ----- 3.3v/5v
 * GND        ----- GND
 *
 * DHT  ----------- Wemos D1 mini
 * Vcc              Vcc
 * Data ( 2 )       D4 ( pullup 10K )
 * NC
 * GND              GND
 */
#include "Arduino.h"
#include "LoRa_E32.h"
#include <DHT.h>
#define DHTTYPE DHT22 //type of DHT
#define DHTPIN D4     // pin DHT
#include <Wire.h>
#include "floatToString.h"

int error=0;

DHT dht(DHTPIN, DHTTYPE); 
// Temperature Variables
float hum_f, temp_f;  // Values read from sensor
//-----start temperature variables
bool conv;
unsigned long oldtime,newtime;
float celsius,previus_celsius;
int hum,previus_hum;
//-----end temperature variables
//
// Adafruit IO
//#define AIO_SERVER      "IP server" //ip server
//#define AIO_SERVERPORT  1883          //porta del server
//#define AIO_USERNAME    "username"   //nome utente del server
//#define AIO_KEY         "passwd" //passwod del server    
char buff[10];

LoRa_E32 e32ttl100(D2, D3); // e32 TX e32 RX
 
void setup() {
  Serial.begin(9600);
  dht.begin();           // initialize temperature sensor
  // Set lamp pin to output 
  delay(400);
 
  
 
  // Startup all pins and UART
  e32ttl100.begin();
 
  // Send message
  ResponseStatus rs = e32ttl100.sendMessage("Hello, world?");
  // Check If there is some problem of successfully send
  Serial.println(rs.getResponseDescription());
  previus_celsius=-999;
  delay(5000);
  Serial.println("Hi, DHT22 TX ready, I'm going to send message!");
}
 
void loop() {
  //++++++++++++++++++++++++++++++++START TEMP+++++++++++++++++++++++++++++++++
//Serial.println("Loop");
  if (conv == false) {
    conv=true;    
    oldtime=millis();
     }

//
//++++++++++++++++++++++++++++++++END TEMP+++++++++++++++++++++++++++++++++
newtime=millis();
// Read Temperature   humidity pressure
if (conv & (newtime-oldtime)> 2000 ) {
//Serial.println("Read from DHT sensor! Conv");
  hum_f = dht.readHumidity();          // Read humidity (percent)
    temp_f = dht.readTemperature();     // Read temperature as Celsius

     if (isnan(hum_f) || isnan(temp_f)) {
      if (error == 0){
      Serial.println("Failed to read from DHT sensor!");
      ResponseStatus rs = e32ttl100.sendMessage("Failed to read from DHT sensor!");
      //error = 1;
      }
      ResponseStatus rs = e32ttl100.sendMessage("Failed to read from DHT sensor!");
      return;
      }
      
conv=false;
  celsius = temp_f;
  celsius=celsius+0.05;
  celsius=int (celsius*10) ;
  celsius=celsius/10.;
 // if (celsius!=previus_celsius) {
                   // if (! temperature.publish(celsius))
                   // Serial.println(F("Failed to publish temperature"));
                    //  else
                     // {
                         Serial.print(F("  Temperature = "));
                         Serial.print(celsius);
                         Serial.print(F(" Celsius, "));
                         Serial.println(F("published!"));
                         previus_celsius=celsius;
                    //}
                 //   }
// humidity
  hum_f = (hum_f+0.5)*10;
  hum=hum_f/10;// round nearest int
  
 // if (hum!=previus_hum) {
                    //if (! humidity.publish(hum))
                    //Serial.println(F("Failed to publish humidity"));
                   //   else
                    //  {
                         Serial.print(F("  humidity = "));
                         Serial.print(hum);
                         Serial.print(F("% "));
                         Serial.println(F("published!"));
                         previus_hum=hum;
                    //}

 
                 // }

      //snprintf (buff, sizeof(buff), "%f", celsius);
      String stA1 (floatToString(buff, celsius, 2)); // convert to string 2 is digit after comma
      String stA2 (floatToString(buff, hum, 2));
      Serial.println("Temp: "+stA1+" Hum: "+stA2);
   ResponseStatus rs = e32ttl100.sendMessage("Temp: "+stA1+" Hum: "+stA2);   
   
    // If something available
  if (e32ttl100.available()>1) {
      // read the String message
    ResponseContainer rc = e32ttl100.receiveMessage();
    // Is something goes wrong print error
    if (rc.status.code!=1){
        rc.status.getResponseDescription();
    }else{
        // Print the data received
        Serial.println(rc.data);
    }
  }
  if (Serial.available()) {
      String input = Serial.readString();
      e32ttl100.sendMessage(input);
  } // end if serial
}
}  // end Loop
// connect to server io via MQTT

/*
void connect() {

  Serial.print(F("Connessione al server... "));

  int8_t ret;

  while ((ret = mqtt.connect()) != 0) {

    switch (ret) {
      case 1: Serial.println(F("Wrong protocol")); break;
      case 2: Serial.println(F("ID rejected")); break;
      case 3: Serial.println(F("Server unavail")); break;
      case 4: Serial.println(F("Bad user/pass")); break;
      case 5: Serial.println(F("Not authed")); break;
      case 6: Serial.println(F("Failed to subscribe")); break;
      default: Serial.println(F("Connection failed")); break;
    }

    if(ret >= 0)
      mqtt.disconnect();

    Serial.println(F("Retrying connection..."));
    delay(5000);

  }

  Serial.println(F("server Connected!"));

}
 */